import {unref, nextTick} from 'vue';
import {defineStore} from 'pinia';
import {router} from '@/router';
import {fetchLogin, fetchUserInfo} from '@/service';
import {useRouterPush} from '@/composables';
import {localStg} from '@/utils';
import {$t} from '@/locales';
import {useTabStore} from '../tab';
import {useRouteStore} from '../route';
import {getToken, getUserInfo, clearAuthStorage} from './helpers';

interface AuthState {
	/** 用户信息 */
	userInfo: Auth.UserInfo;
	/** 用户token */
	token: string;
	/** 登录的加载状态 */
	loginLoading: boolean;
}

export const useAuthStore = defineStore('auth-store', {
	state: (): AuthState => ({
		userInfo: getUserInfo(),
		token: getToken(),
		loginLoading: false
	}),
	getters: {
		/** 是否登录 */
		isLogin(state) {
			return Boolean(state.token);
		}
	},
	actions: {
		/** 重置auth状态 */
		resetAuthStore() {
			const {toLogin} = useRouterPush(false);
			const {resetTabStore} = useTabStore();
			const {resetRouteStore} = useRouteStore();
			const route = unref(router.currentRoute);

			clearAuthStorage();
			this.$reset();

			if (route.meta.requiresAuth) {
				toLogin();
			}

			nextTick(() => {
				resetTabStore();
				resetRouteStore();
			});
		},
		/**
		 * 处理登录后成功或失败的逻辑
		 * @param loginResult - 登录结果
		 */
		async handleActionAfterLogin(loginResult: boolean) {
			const route = useRouteStore();
			const {toLoginRedirect} = useRouterPush(false);

			// 获取用户信息
			const {data} = await fetchUserInfo();
			if (data) {
				data.userRole = 'super';
				// 成功后把用户信息存储到缓存中
				localStg.set('userInfo', data);
				// 更新状态
				const token = localStg.get('token');
				this.userInfo = data;
				this.token = token ? token : '';
				await route.initAuthRoute();
				// 跳转登录后的地址
				toLoginRedirect();
				// 登录成功弹出欢迎提示
				if (route.isInitAuthRoute) {
					window.$notification?.success({
						title: $t('page.login.common.loginSuccess'),
						content: $t('page.login.common.welcomeBack', {nickname: this.userInfo.nickname}),
						duration: 3000
					});
				}
				return;
			}
			// 不成功则重置状态
			this.resetAuthStore();
		},
		/**
		 * 登录
		 * @param username
		 * @param password - 密码
		 */
		async login(username: string, password: string) {
			this.loginLoading = true;
			const {data} = await fetchLogin(username, password);
			console.log('data = ', data)
			console.log("设置 token 缓存： ", localStg.get('token'))
			if (data) {
				await this.handleActionAfterLogin(data);
			}
			this.loginLoading = false;
		},
		/**
		 * 更换用户权限(切换账号)
		 * @param userRole
		 */
		async updateUserRole(userRole: Auth.RoleType) {
			const {resetRouteStore, initAuthRoute} = useRouteStore();

			const accounts: Record<Auth.RoleType, { userName: string; password: string }> = {
				super: {
					userName: 'Super',
					password: 'super123'
				},
				admin: {
					userName: 'Admin',
					password: 'admin123'
				},
				user: {
					userName: 'User01',
					password: 'user01123'
				}
			};
			const {userName, password} = accounts[userRole];
			const {data} = await fetchLogin(userName, password);
			if (data) {
				resetRouteStore();
				initAuthRoute();
			}
		}
	}
});
